<?php

class BDealcallbackPayment extends UWorkletBehavior {

	public function beforeSave() {

		$this->getOwner()->amount = 0;
		$this->getOwner()->items = array();

		$items = isset($_POST['items']) ? $_POST['items'] : null;
		if (!$items || !is_array($items) || !count($items))
			return $this->getOwner()->model->addError('type', $this->getOwner()->t('Cart is empty.'));

		$dealId = null;
		foreach ($items as $module => $item) {
			foreach ($item as $id => $quantity) {
				$dealId = $id;
				if (($error = wm()->get($module . '.order')->verify($id, $quantity)) !== true) {
					return $this->getOwner()->model->addError('type', $error);
				}
			}
		}

		if ($this->getOwner()->amount < 0)
			return $this->getOwner()->model->addError('type', $this->t('Total amount may not be negative.'));

		if ($this->getOwner()->amount == 0)
			$this->getOwner()->model->type = 'system';

		$order = wm()->get('payment.order')->place($items, $this->getOwner()->amount, $this->getOwner()->model->type);
		$processor = 'payment.' . $this->getOwner()->model->type . '.' . $this->getOwner()->transactionType;

		$options = array();

		if (count($items) == 1) {
			$dealCallback = MDealcallback::model()->findByPk($dealId);

			if ($dealCallback && $dealCallback->callbackUrl) {
				$options["return"] = HelperUrl::addhttp($dealCallback->callbackUrl);
			}
		}
		wm()->get($processor)->run($this->getOwner()->items, $order->id, $options);
		return false;
	}
}